import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import '../../core/app_config.dart';
import '../../services/statistics_service.dart';

/// 统计分析界面
class StatisticsScreen extends StatefulWidget {
  const StatisticsScreen({super.key});

  @override
  State<StatisticsScreen> createState() => _StatisticsScreenState();
}

class _StatisticsScreenState extends State<StatisticsScreen>
    with SingleTickerProviderStateMixin {
  final Logger _logger = Logger();
  final StatisticsService _statisticsService = StatisticsService();
  
  late TabController _tabController;
  bool _isLoading = false;
  String? _errorMessage;
  
  // 总体统计数据
  Map<String, dynamic>? _overallStats;
  
  // 趋势分析数据
  Map<String, dynamic>? _trendData;
  String _selectedTimeUnit = 'month';
  int _selectedLimit = 12;
  
  // 对比分析数据
  Map<String, dynamic>? _comparisonData;
  String _selectedComparisonType = 'process';
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _loadOverallStatistics();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('统计分析'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '总体统计'),
            Tab(text: '趋势分析'),
            Tab(text: '对比分析'),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.file_download),
            onPressed: _exportReport,
            tooltip: '导出报表',
          ),
        ],
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildOverallStatisticsTab(),
          _buildTrendAnalysisTab(),
          _buildComparisonAnalysisTab(),
        ],
      ),
    );
  }

  /// 构建总体统计标签页
  Widget _buildOverallStatisticsTab() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return _buildErrorView();
    }

    if (_overallStats == null) {
      return const Center(child: Text('暂无数据'));
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 基础统计卡片
          _buildBasicStatsCard(),
          const SizedBox(height: 16),
          
          // 本月统计卡片
          _buildMonthlyStatsCard(),
          const SizedBox(height: 16),
          
          // 工艺类型统计卡片
          _buildProcessStatsCard(),
        ],
      ),
    );
  }

  /// 构建基础统计卡片
  Widget _buildBasicStatsCard() {
    final basicStats = _overallStats!['basic_stats'] as Map<String, dynamic>;
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '基础统计',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _buildStatRow('总记录数', '${(basicStats['total_records'] as int?)?.toString() ?? '0'} 条'),
            _buildStatRow('总产能', '${(basicStats['total_production'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
            _buildStatRow('总能耗', '${(basicStats['total_energy_consumption'] as num?)?.toStringAsFixed(2) ?? '0.00'} kWh'),
            _buildStatRow('总碳排放', '${(basicStats['total_carbon_emission'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
          ],
        ),
      ),
    );
  }

  /// 构建本月统计卡片
  Widget _buildMonthlyStatsCard() {
    final monthlyStats = _overallStats!['monthly_stats'] as Map<String, dynamic>;
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '本月统计',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _buildStatRow('本月记录数', '${(monthlyStats['monthly_records'] as int?)?.toString() ?? '0'} 条'),
            _buildStatRow('本月产能', '${(monthlyStats['monthly_production'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
            _buildStatRow('本月碳排放', '${(monthlyStats['monthly_carbon_emission'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
          ],
        ),
      ),
    );
  }

  /// 构建工艺类型统计卡片
  Widget _buildProcessStatsCard() {
    final processStats = _overallStats!['process_stats'] as List<dynamic>;
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '工艺类型统计',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            if (processStats.isEmpty)
              const Text('暂无工艺类型数据')
            else
              ...processStats.map((process) => _buildProcessStatRow(process)),
          ],
        ),
      ),
    );
  }

  /// 构建统计行
  Widget _buildStatRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(color: Colors.grey)),
          Text(
            value,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建工艺统计行
  Widget _buildProcessStatRow(Map<String, dynamic> process) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              (process['process_type'] as String?) ?? '未知工艺',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: _buildStatItem('记录数', '${(process['record_count'] as int?)?.toString() ?? '0'}'),
                ),
                Expanded(
                  child: _buildStatItem('总产能', '${(process['total_production'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
                ),
                Expanded(
                  child: _buildStatItem('总碳排放', '${(process['total_carbon_emission'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
        Text(
          value,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  /// 构建趋势分析标签页
  Widget _buildTrendAnalysisTab() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 筛选控件
          _buildTrendFilters(),
          const SizedBox(height: 16),
          
          // 趋势数据
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _errorMessage != null
                    ? _buildErrorView()
                    : _trendData == null
                        ? const Center(child: Text('暂无趋势数据'))
                        : _buildTrendDataView(),
          ),
        ],
      ),
    );
  }

  /// 构建趋势筛选控件
  Widget _buildTrendFilters() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '筛选条件',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: DropdownButtonFormField<String>(
                    value: _selectedTimeUnit,
                    decoration: const InputDecoration(
                      labelText: '时间单位',
                      border: OutlineInputBorder(),
                    ),
                    items: const [
                      DropdownMenuItem(value: 'day', child: Text('日')),
                      DropdownMenuItem(value: 'month', child: Text('月')),
                      DropdownMenuItem(value: 'year', child: Text('年')),
                    ],
                    onChanged: (value) {
                      if (value != null) {
                        setState(() {
                          _selectedTimeUnit = value;
                        });
                        _loadTrendData();
                      }
                    },
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: DropdownButtonFormField<int>(
                    value: _selectedLimit,
                    decoration: const InputDecoration(
                      labelText: '数据点数量',
                      border: OutlineInputBorder(),
                    ),
                    items: const [
                      DropdownMenuItem(value: 7, child: Text('7个')),
                      DropdownMenuItem(value: 12, child: Text('12个')),
                      DropdownMenuItem(value: 24, child: Text('24个')),
                    ],
                    onChanged: (value) {
                      if (value != null) {
                        setState(() {
                          _selectedLimit = value;
                        });
                        _loadTrendData();
                      }
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建趋势数据视图
  Widget _buildTrendDataView() {
    final trendData = _trendData!['trend_data'] as List<dynamic>;
    
    if (trendData.isEmpty) {
      return const Center(child: Text('暂无趋势数据'));
    }

    return ListView.builder(
      itemCount: trendData.length,
      itemBuilder: (context, index) {
        final trend = trendData[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 8),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '时间周期: ${trend['time_period']}',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: _buildStatItem('记录数', '${(trend['record_count'] as int?)?.toString() ?? '0'}'),
                    ),
                    Expanded(
                      child: _buildStatItem('总产能', '${(trend['total_production'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
                    ),
                    Expanded(
                      child: _buildStatItem('总碳排放', '${(trend['total_carbon_emission'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建对比分析标签页
  Widget _buildComparisonAnalysisTab() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 筛选控件
          _buildComparisonFilters(),
          const SizedBox(height: 16),
          
          // 对比数据
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _errorMessage != null
                    ? _buildErrorView()
                    : _comparisonData == null
                        ? const Center(child: Text('暂无对比数据'))
                        : _buildComparisonDataView(),
          ),
        ],
      ),
    );
  }

  /// 构建对比筛选控件
  Widget _buildComparisonFilters() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '对比类型',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            DropdownButtonFormField<String>(
              value: _selectedComparisonType,
              decoration: const InputDecoration(
                labelText: '对比维度',
                border: OutlineInputBorder(),
              ),
              items: const [
                DropdownMenuItem(value: 'process', child: Text('工艺类型对比')),
                DropdownMenuItem(value: 'time', child: Text('时间对比')),
                DropdownMenuItem(value: 'region', child: Text('地区对比')),
              ],
              onChanged: (value) {
                if (value != null) {
                  setState(() {
                    _selectedComparisonType = value;
                  });
                  _loadComparisonData();
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 构建对比数据视图
  Widget _buildComparisonDataView() {
    final comparisonData = _comparisonData!['comparison_data'] as List<dynamic>;
    
    if (comparisonData.isEmpty) {
      return const Center(child: Text('暂无对比数据'));
    }

    return ListView.builder(
      itemCount: comparisonData.length,
      itemBuilder: (context, index) {
        final comparison = comparisonData[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 8),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  comparison['comparison_label'] ?? '未知',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: _buildStatItem('记录数', '${(comparison['record_count'] as int?)?.toString() ?? '0'}'),
                    ),
                    Expanded(
                      child: _buildStatItem('总产能', '${(comparison['total_production'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
                    ),
                    Expanded(
                      child: _buildStatItem('总碳排放', '${(comparison['total_carbon_emission'] as num?)?.toStringAsFixed(2) ?? '0.00'} 吨'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            Text(
              _errorMessage ?? '加载失败',
              style: const TextStyle(color: Colors.red),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _retry,
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }

  /// 加载总体统计数据
  Future<void> _loadOverallStatistics() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      _logger.d('开始加载总体统计数据');
      final stats = await _statisticsService.getOverallStatistics();
      setState(() {
        _overallStats = stats;
        _isLoading = false;
      });
      _logger.i('总体统计数据加载成功');
    } catch (e) {
      _logger.e('加载总体统计数据失败: $e');
      setState(() {
        _errorMessage = '加载统计数据失败: $e';
        _isLoading = false;
      });
    }
  }

  /// 加载趋势数据
  Future<void> _loadTrendData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      _logger.d('开始加载趋势数据: $_selectedTimeUnit, $_selectedLimit');
      final data = await _statisticsService.getTrendAnalysis(
        timeUnit: _selectedTimeUnit,
        limit: _selectedLimit,
      );
      setState(() {
        _trendData = data;
        _isLoading = false;
      });
      _logger.i('趋势数据加载成功');
    } catch (e) {
      _logger.e('加载趋势数据失败: $e');
      setState(() {
        _errorMessage = '加载趋势数据失败: $e';
        _isLoading = false;
      });
    }
  }

  /// 加载对比数据
  Future<void> _loadComparisonData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      _logger.d('开始加载对比数据: $_selectedComparisonType');
      final data = await _statisticsService.getComparisonAnalysis(
        comparisonType: _selectedComparisonType,
      );
      setState(() {
        _comparisonData = data;
        _isLoading = false;
      });
      _logger.i('对比数据加载成功');
    } catch (e) {
      _logger.e('加载对比数据失败: $e');
      setState(() {
        _errorMessage = '加载对比数据失败: $e';
        _isLoading = false;
      });
    }
  }

  /// 重试加载
  void _retry() {
    switch (_tabController.index) {
      case 0:
        _loadOverallStatistics();
        break;
      case 1:
        _loadTrendData();
        break;
      case 2:
        _loadComparisonData();
        break;
    }
  }

  /// 导出报表
  Future<void> _exportReport() async {
    try {
      _logger.d('开始导出报表');
      
      String reportType;
      Map<String, dynamic>? parameters;
      
      switch (_tabController.index) {
        case 0:
          reportType = 'overall';
          break;
        case 1:
          reportType = 'trend';
          parameters = {
            'time_unit': _selectedTimeUnit,
            'limit': _selectedLimit,
          };
          break;
        case 2:
          reportType = 'comparison';
          parameters = {
            'comparison_type': _selectedComparisonType,
          };
          break;
        default:
          return;
      }
      
      final csvContent = await _statisticsService.exportStatisticsReport(
        reportType: reportType,
        parameters: parameters,
      );
      
      // 保存文件
      final result = await FilePicker.platform.saveFile(
        dialogTitle: '保存统计报表',
        fileName: 'statistics_report_${DateTime.now().millisecondsSinceEpoch}.csv',
        allowedExtensions: ['csv'],
      );
      
      if (result != null) {
        final file = File(result);
        await file.writeAsString(csvContent);
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('报表已保存到: ${file.path}'),
              backgroundColor: Colors.green,
            ),
          );
        }
        
        _logger.i('报表导出成功: ${file.path}');
      }
    } catch (e) {
      _logger.e('导出报表失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('导出报表失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
} 